"use client";
import { useEffect, useRef, forwardRef, useImperativeHandle } from "react";
// @ts-ignore - Reveal.js doesn't have TypeScript definitions
import Reveal from "reveal.js";
// @ts-ignore
import Markdown from "reveal.js/plugin/markdown/markdown.esm.js";
// @ts-ignore
import Highlight from "reveal.js/plugin/highlight/highlight.esm.js";
// @ts-ignore
import Notes from "reveal.js/plugin/notes/notes.esm.js";

// Props interface for the component
interface RevealPresentationProps {
  content: string; // Markdown content for the presentation
  onSlideChange?: (index: number) => void; // Callback when slide changes
}

// Handle interface for external control
export interface RevealPresentationHandle {
  goToSlide: (index: number) => void; // Method to navigate to specific slide
}

// Main presentation component with forwardRef
const RevealPresentation = forwardRef<RevealPresentationHandle, RevealPresentationProps>(
  ({ content, onSlideChange }, ref) => {
    const revealRef = useRef<HTMLDivElement>(null); // Ref for the container
    const revealInstance = useRef<Reveal.Api | null>(null); // Ref for Reveal instance

    // Expose methods to parent component
    useImperativeHandle(ref, () => ({
      goToSlide: (index: number) => {
        if (revealInstance.current) {
          revealInstance.current.slide(index);
        }
      },
    }));

    // 添加全局错误处理
    useEffect(() => {
      const handleError = (event: ErrorEvent) => {
        // 捕获并抑制权限相关错误
        if (event.message.includes('Permissions check failed') ||
            event.message.includes('Permission denied') ||
            event.message.includes('fullscreen')) {
          console.warn('Fullscreen permission error suppressed:', event.message);
          event.preventDefault();
          return false;
        }
      };

      const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
        if (event.reason?.message?.includes('Permissions check failed') ||
            event.reason?.message?.includes('Permission denied') ||
            event.reason?.message?.includes('fullscreen')) {
          console.warn('Fullscreen permission promise rejection suppressed:', event.reason);
          event.preventDefault();
        }
      };

      window.addEventListener('error', handleError);
      window.addEventListener('unhandledrejection', handleUnhandledRejection);

      return () => {
        window.removeEventListener('error', handleError);
        window.removeEventListener('unhandledrejection', handleUnhandledRejection);
      };
    }, []);

    // Initialize Reveal.js on mount
    useEffect(() => {
      if (!revealRef.current) return;

      try {
        // Create new Reveal instance with configuration
        revealInstance.current = new Reveal(revealRef.current, {
          autoAnimate: true,
          plugins: [Markdown, Highlight, Notes],
          controls: true,
          controlsTutorial: true,
          controlsLayout: 'bottom-right',
          controlsBackArrows: 'faded',
          progress: true,
          fullscreen: true,
          embedded: true,
          transition: 'slide', // Slide transition style
          transitionSpeed: 'default', // Transition speed (fast/slow/default)
          backgroundTransition: 'fade', // Background transition
        });

        revealInstance.current.initialize().catch((error: unknown) => {
          console.warn('Reveal.js initialization error:', error);
        });

        // Add slide change listener if callback provided
        if (onSlideChange) {
          revealInstance.current.on('slidechanged', (event: { indexh: number; }) => {
            onSlideChange(event.indexh);
          });
        }

        // 添加全屏事件监听器
        revealInstance.current.on('fullscreenchange', () => {
          console.log('Fullscreen state changed');
        });

      } catch (error) {
        console.error('Error initializing Reveal.js:', error);
      }

      // Cleanup on unmount
      return () => {
        try {
          if (revealInstance.current?.isReady()) {
            revealInstance.current.destroy();
          }
        } catch (error) {
          console.warn('Error destroying Reveal.js:', error);
        }
      };
    }, []);

    // Handle content updates
    useEffect(() => {
      if (revealInstance.current) {
        try {
          // 保存当前幻灯片索引
          const currentIndex = revealInstance.current.getState().indexh;

          // 完全移除旧的slides
          const slidesContainer = revealRef.current?.querySelector('.slides');
          if (slidesContainer) {
            slidesContainer.innerHTML = `
              <section data-markdown
                       data-separator-notes="^note:"
                       data-separator-vertical="^---">
                <textarea data-template>${content}</textarea>
              </section>
            `;
          }

          // 安全销毁实例
          if (revealInstance.current.isReady()) {
            revealInstance.current.destroy();
          }
          
          // 重新初始化
          revealInstance.current = new Reveal(revealRef.current!, {
            autoAnimate: true,
            plugins: [Markdown, Highlight, Notes],
            controls: true,
            controlsTutorial: true,
            controlsLayout: 'bottom-right',
            controlsBackArrows: 'faded',
            progress: true,
            fullscreen: true,
            embedded: true
          });
        
          revealInstance.current.initialize().then(() => {
            // 恢复之前的幻灯片位置
            revealInstance.current?.slide(currentIndex);
            console.log(currentIndex);
          }).catch((error: unknown) => {
            console.warn('Reveal.js re-initialization error:', error);
          });
        } catch (error) {
          console.error('Error updating Reveal.js content:', error);
        }
      }
    }, [content]);

    // Render presentation container
    return (
      <div className="reveal reveal-edit [font-family:'AlibabaPuHuiTi','Noto Sans SC','Microsoft YaHei',sans-serif] w-full " ref={revealRef}>
        <div className="slides">
          <section
            data-markdown=""
            data-separator-notes="^note:"
            data-separator-vertical="^---"
          >
            <textarea 
              data-template
              defaultValue={content}
            >
              </textarea>
          </section>
        </div>
      </div>
    );
  }
);

// Set display name for debugging
RevealPresentation.displayName = 'RevealPresentation';

export default RevealPresentation;